const Base = require('./base.js');
const moment = require('moment');
//积分商城
module.exports = class extends Base {
    /**
     * index action
     * @return {Promise} []
     */
    async indexAction() {
        const page = this.get('page') || 1;
        const size = this.get('size') || 6;
        const sortField = this.get('sortfield') || 'sort_order asc,order_time desc';
        const goodsname = this.get('coupon_name') || '';
        const category_id = this.get('category_id') || '';
        const goods_id = this.get('goods_id') || '';
        const state = this.get('state') || '';
        let seachdata = { id:['>',0],is_delete:0}, timesearch = {};
        if(category_id){
            seachdata['category_id'] = category_id;
        }
        if(goods_id){
            seachdata['goods_id'] = goods_id;
        }
        if (goodsname) {
            seachdata['coupon_name'] = ['like', `%${goodsname}%`];
        }

        const model = this.model('coupon');
        const data = await model.where(seachdata)
        .order([sortField]).page(page, size).countSelect();
        // .order([sortField]).select();
        //库存，方便显示已售罄
        for(const item of data.data){
            const redeem = await this.model('coupon_user').where({coupon_id:item.id}).count();
            let acount = item.total -redeem;
            item.goods_number= acount?acount:0;//库存
        }
        return this.success(data);
    }

     /**
     * 我的优惠券
     * @return {Promise} []
     */
    async ownerAction() {
        const page = this.post('page') || 1;
        const size = this.post('size') || 6;
        const sortField = this.post('sortfield') || 'addtime';
        const goodsname = this.post('coupon_name') || '';
        const category_id = this.post('category_id') || '';
        const goods_id = this.post('goods_id') || '';
        const state = this.post('state') || [];
        let seachdata = { user_id:think.userId,is_delete:0}, timesearch = {};
        if(category_id){
            seachdata['category_id'] = category_id;
        }
        if(goods_id){
            seachdata['goods_id'] = goods_id;
        }
        if (goodsname) {
            seachdata['coupon_name'] = ['like', `%${goodsname}%`];
        }
        if(state&&state.length>0){
            seachdata['status'] = ['in', state];
        }else{
            seachdata['status'] = 0;
        }

        const model = this.model('coupon_user');
        const data = await model.where(seachdata)
        .order([sortField]).page(page, size).countSelect();
        // .order([sortField]).select();
        //库存，方便显示已售罄
        for(const item of data.data){//显示失效时间
            item.addtime= moment.unix(item.addtime).format('YYYY.MM.DD HH:mm');
            item.failtime= moment.unix(item.failtime-1).format('YYYY.MM.DD HH:mm');//失效时间
            item.nowstatus = await model.getnowStatusText(item.status,item.is_delete,item.failtime);//状态
        }
        return this.success(data);
    }


    async detailAction() {//进入详情页
        const model = this.model('coupon');
        const id = this.get('id');
        const info=await model.where({id: id,is_delete:0}).find();
        if(think.isEmpty(info)){
			return this.fail(400,'该商品不存在或已下架');
        }
        const redeem = await this.model('coupon_user').where({coupon_id:id}).count();
        let acount = info.total -redeem;
         info.goods_number= acount?acount:0;//库存
        return this.success(info);
    }
     async readAction() {
        const model = this.model('coupon');
        const id = this.get('id');
        const data=await model.where({id: id}).find();
        return this.success(data);
    }

    async orderAction() {//进入订单提交详情页
        const model = this.model('coupon');
        const id = this.post('id');
        const number = this.post('number');
        if(number<1){
    return this.fail(400, '请输入正确的数量');
        }
        const info=await model.where({id: id,is_delete:0}).find();
        if(think.isEmpty(info)){
			return this.fail(400,'该商品不存在或已下架');
        }
        const redeem = await this.model('coupon_user').where({coupon_id:id}).count();
        let acount = info.total -redeem;
        if(acount<0){
    return this.fail(400, '库存不足');
        }
        info.number=number


        return this.success({
            info:info,
            count:number,
            totalPrice:parseInt(info.req_points*number)
        });
    }

    async submitAction() {//提交订单
        const model = this.model('coupon');
        const id = this.post('id');
        const number = this.post('number')||1;
        let totalPrice = this.post('totalPrice');
        if(id<1){
            return this.fail(400, '请输入正确的id');
        }
        if(totalPrice<0){
            return this.fail(400, '无效的总积分价格');
        }
        if(number<1){
            return this.fail(400, '请输入正确的数量');
        }
        const info=await model.where({id: id,is_delete:0}).find();
        if(think.isEmpty(info)){
			return this.fail(400,'该商品不存在或已下架');
        }
        if(parseInt(totalPrice/number)!=info.req_points){
            return this.fail(400,'优惠券积分发生变化，请重新下单');
        }
        const redeem = await this.model('coupon_user').where({coupon_id:id}).count();
        let acount = info.total -redeem;
        if(acount<0){
            return this.fail(400, '库存不足');
        }
        const userInfo = await this.model('user').where({id:think.userId}).find();
        if(totalPrice>userInfo.integral){
            return this.fail(400, '你的积分不足，兑换失败');
        }
        const uredeem = await this.model('coupon_user').where({coupon_id:id,user_id:userInfo.id}).count();
        if(info.limit&&uredeem+number>info.limit){
            return this.fail(400, info.limit-uredeem>0?'兑换数量超过上限，你还可兑'+info.limit-uredeem+'件':'兑换数量超过上限，你还可兑0件');
        }

        let addDatas=[],now = parseInt(new Date().getTime()/1000);
        for(let i=0;i<number;i++){
            addDatas.push({
                coupon_id:info.id,
	            user_id:userInfo.id,
	            goods_id:info.goods_id,
	            category_id:info.category_id,
	            coupon_name:info.coupon_name,
	            req_points:info.req_points,
	            coupon_value:info.coupon_value,
	            tips:info.tips,
	            min_price:info.min_price,
	            pic_url:info.pic_url,
	            is_delete:0,
	            type:info.type,
	            addtime:now,
                  failtime:moment(moment().add(info.coupon_time, "day").format('YYYY-MM-DD')).valueOf()/1000
            });
        }
        await this.model('coupon_user').addMany(addDatas);
        await this.model('user').where({id: think.userId}).decrement('integral',totalPrice);
        let ti_id = await this.model('task_integral').add({
            user_id: think.userId,
            integral:totalPrice*-1,
            reason:'兑换优惠券',
            is_finish:1
        });
        await this.model('coupon_record').add({//优惠券兑换记录
            user_id: think.userId,
            coupon_id:info.id,
            req_points:info.req_points,
	        number:number,
	        total_points:totalPrice, 
            ti_i:ti_id,
            add_time:now
        });
        return this.success({
           orderInfo:info
        });
    }




};